package com.esreport.logstash.cutter;

import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @author xuweiwei
 * @date 2018/12/21
 */
public class WrapCutter implements Cutter {

    @Override
    public String next(RandomAccessFile f) throws IOException {
        String result = null;
        do {
            result = nextLine(f);
        } while (result != null && result.trim().length() == 0);
        return result;
    }


    public String nextLine(RandomAccessFile f) throws IOException {
        StringBuffer input = new StringBuffer();
        int c = -1;
        boolean eol = false;
        long pos = f.getFilePointer();
        while (!eol) {
            switch (c = f.read()) {
                case -1:
                    eol = true;
                    break;
                case '\n':
                    eol = true;
                    break;
                case '\r':
                    eol = true;
                    long cur = f.getFilePointer();
                    if ((f.read()) != '\n') {
                        f.seek(cur);
                    }
                    break;
                default:
                    input.append((char) c);
                    break;
            }
        }
        if (c == -1) {
            f.seek(pos);
            return null;
        }
        return input.toString();
    }
}
